package com.app.web;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

@Controller
public class FileOperateUtil {
	@RequestMapping("/fileOperate.shtml")
	public String show(HttpServletRequest request) {
		return "fileOperate.vm";
	}

	@RequestMapping("/upload.shtml")
	public String upload(Model model,@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IllegalStateException, IOException {
		Logger logger = LoggerFactory.getLogger(Go.class);
		long startTime = System.currentTimeMillis();
		/*
		// 将当前上下文初始化给 CommonsMutipartResolver （多部分解析器）
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 检查form中是否有enctype="multipart/form-data"
		if (multipartResolver.isMultipart(request)) {
			// 将request变成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 获取multiRequest 中所有的文件名
			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				// 一次遍历所有文件
				MultipartFile file = multiRequest.getFile(iter.next().toString());
				if (file != null) {
					String path = "C:/Users/Mr.L/Desktop/" + file.getOriginalFilename();
					logger.info("路径：" + path);
					// 上传
					file.transferTo(new File(path));
				}
			}
		}
		*/
		
		if (file != null) {
			//webAppPath = "D:\Apache Software Foundation\Tomcat 9.0\webapps\app\"   request.getContextPath() = "/app"
			String basepath = request.getSession().getServletContext().getRealPath("/");
			String path = basepath + "WEB-INF/upload/" + file.getOriginalFilename();
			logger.info("path:" + path);
			// 上传
			file.transferTo(new File(path));
		}
		
		long endTime = System.currentTimeMillis();
		logger.info("上传用时：" + String.valueOf(endTime - startTime) + "ms");
		model.addAttribute("result", "success");
		return "fileOperate.vm";
	}

	@RequestMapping(value = "/downLoad.shtml")
	public ResponseEntity<byte[]> download(@RequestParam("name") String name, @RequestParam("filePath") String filePath)
			throws IOException {
		Logger logger = LoggerFactory.getLogger(Go.class);
		File file = new File(filePath);
		HttpHeaders headers = new HttpHeaders();
		String fileName = new String(name.getBytes("UTF-8"), "iso-8859-1");// 为了解决中文名称乱码问题
		logger.info("路径：" + filePath);
		logger.info("文件名：" + fileName);
		headers.setContentDispositionFormData("attachment", fileName);
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
	}

}
